import React, { useEffect, useRef, useState } from 'react';
import { Card, Col, Row, List, Avatar, Drawer } from 'antd';
// import { BarChartOutlined } from '@ant-design/icons';
import { BarChartOutlined, EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import axios from 'axios';
import * as echarts from 'echarts';
import _ from "lodash"

const { Meta } = Card;

export default function Home() {
  const { role: { roleName }, region, username } = JSON.parse(localStorage.getItem("token"))

  const [viewList, setViewList] = useState([])
  const [starList, setStarList] = useState([])
  const [allList, setAllList] = useState([])
  const [open, setOpen] = useState(false);
  const [pieChart, setpieChart] = useState(null);
  const barRef = useRef()
  const pieRef = useRef()

  useEffect(() => {
    axios.get("/news?punlishState=2&_expand=category&_sort=view&_order=desc&_limit=8").then(res => {
      setViewList(res.data)
    })
  }, [])

  useEffect(() => {
    axios.get("/news?punlishState=2&_expand=category&_sort=star&_order=desc&_limit=8").then(res => {
      setStarList(res.data)
    })
  }, [])

  useEffect(() => {
    axios.get("/news?punlishState=2&_expand=category").then(res => {
      renderBar(_.groupBy(res.data, item => item.category.title))
      setAllList(res.data)
    })

    return () => {// 销毁时关闭自适应
      window.onresize = null
    }
  }, [])

  const renderBar = (obj) => {

    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(barRef.current)

    // 指定图表的配置项和数据
    var option = {
      title: {
        text: '新闻分类图示'
      },
      tooltip: {},
      legend: {
        data: ['数量']
      },
      xAxis: {
        data: Object.keys(obj),
        axisLabel: {
          rotate: 30,
          interval: 0

        },
      },
      yAxis: {
        minInterval: 2
      },
      series: [
        {
          name: '数量',
          type: 'bar',
          data: Object.values(obj).map(item => item.length)
        }
      ]
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);

    // 随着屏幕尺寸自适应
    window.onresize = () => {
      myChart.resize()
    }
  }

  const renderPie = () => {
    //数据处理
    const currentList = allList.filter(item => item.author === username)
    const groupObj = _.groupBy(currentList, item => item.category.title)
    const list = []
    for (var i in groupObj) {
      list.push({
        name: i,
        value: groupObj[i].length
      })
    }

    var myChart
    if (!pieChart) {//避免重复创建
      myChart = echarts.init(pieRef.current)
      setpieChart(myChart)
    } else {
      myChart = pieChart
    }

    // 指定图表的配置项和数据
    var option = {
      title: {
        text: '当前用户新闻分类图示',
        subtext: 'Fake Data',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '发布数量',
          type: 'pie',
          radius: '50%',
          // data: [
          //   { value: 1048, name: 'Search Engine' },
          //   { value: 300, name: 'Video Ads' }
          // ],
          data: list,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);

    // 随着屏幕尺寸自适应
    window.onresize = () => {
      myChart.resize()
    }
  }

  const showDrawer = () => {
    setOpen(true);
    //先打开再渲染
    setTimeout(() => {
      renderPie()
    }, 0.5)
  };
  const onClose = () => {
    setOpen(false);

  };

  return <>
    <Row gutter={16}>
      <Col span={8}>
        {/* <Card > */}
        {/* Card content */}
        <List
          size="small"
          header={<div>用户最常浏览 <BarChartOutlined /></div>}
          footer={<div>Footer</div>}
          bordered
          dataSource={viewList}
          renderItem={(item) => <List.Item><a href={`#/news-manage/preview/${item.id}`} >{item.title}</a></List.Item>}
        />
        {/* </Card> */}
      </Col>
      <Col span={8}>
        <List
          size="small"
          header={<div>用户点赞最多 <BarChartOutlined /></div>}
          footer={<div>Footer</div>}
          bordered
          dataSource={starList}
          renderItem={(item) => <List.Item><a href={`#/news-manage/preview/${item.id}`} >{item.title}</a></List.Item>}
        />
        {/* </Card> */}
      </Col>
      <Col span={8}>
        <Card
          cover={
            <img
              alt="example"
              src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
            />
          }
          actions={[
            <SettingOutlined key="setting" onClick={showDrawer} />,
            <EditOutlined key="edit" />,
            <EllipsisOutlined key="ellipsis" />,
          ]}
        >
          <Meta
            avatar={<Avatar src="https://xsgames.co/randomusers/avatar.php?g=pixel" />}
            title={username}
            description={
              <>
                <b>{region ? region : "全球"}</b>
                <span style={{ paddingLeft: "10px" }}>{roleName}</span>
              </>
            }
          />
        </Card>
      </Col>
    </Row>
    <Row gutter={16}>
      {/* <!-- 为 ECharts 准备一个定义了宽高的 DOM --> */}
      <div ref={barRef} style={{ width: "100%", height: "400px", marginTop: "30px" }}></div>
    </Row>
    <Drawer title="个人新闻分类" onClose={onClose} open={open} width="600px">
      {/* <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p> */}
      <div ref={pieRef} style={{ width: "100%", height: "400px", marginTop: "30px" }}></div>
    </Drawer>
  </>
}